﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using wsn.model;
using MySql.Data.MySqlClient;
namespace wsn.dao
{
public class SensorDao
{
    private SortedList<int, Sensor> li = new SortedList<int, Sensor>();

    //底层根据节点内网ID寻找所属节点，如果不存在则创建
    public Sensor findSensor(int InsideId, int type)
    {
        Sensor p;
        lock(li){
            if (li.ContainsKey(InsideId))
                li.TryGetValue(InsideId, out p);
            else
            {
                p = new Sensor();
                //todo:其他初始化逻辑
                li.Add(InsideId, p);
                saveOrUpdate(p);//
            }
        }
        return p;
    }

    //为节点增加数据到达时的处理函数
    public Boolean addEvent(String ipv6, DataReceive e)
    {
        //暂时不做
        return false;
    }

    private void saveOrUpdate(Sensor sensor)
    {
        //todo:将数据保存在数据库中
        string query = "insert into sensor(type_name,ipv6,inside_id,save_distance) values('" + sensor.Type.Name + "','" +
                        sensor.Ipv6 + "','" + sensor.InsideId + "','" + sensor.SaveDistance + "'";
        Daofactory.db.ExeNoneQuery(query);
    }

    public void loadSensors()
    {
        //todo:加载数据到内存中
        Sensor temp = new Sensor();
        string query = "select id,type_name,ipv6,inside_id,save_distance from sensor";
        MySqlDataReader reader = Daofactory.db.ExeQuery(query);
        while (reader.Read())
        {
            temp.Id = reader.GetInt32(0);
            temp.Type.Name = reader.GetString(1);
            temp.Type.Id = reader.GetInt32(0);
            temp.Ipv6 = reader.GetString(2);
            temp.InsideId = reader.GetInt32(3);
            temp.SaveDistance = reader.GetInt32(4);
            li.Add(temp.InsideId, temp);
        }
        reader.Close();
    }

    public void storeSensors()
    {
        //todo：如果需要，将所有节点数据更新到数据库中
    }
}
}
